package com.zbkj.front.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bx.imcommon.model.IMGroupMessage;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.*;
import com.zbkj.common.model.community.CommunityTopic;
import com.zbkj.common.model.merchant.Merchant;
import com.zbkj.common.model.merchant.MerchantCategory;
import com.zbkj.common.model.product.MerchantProductGuaranteeGroup;
import com.zbkj.common.model.product.Product;
import com.zbkj.common.model.together.*;
import com.zbkj.common.model.user.User;
import com.zbkj.common.model.user.UserTag;
import com.zbkj.common.model.wechat.video.PayComponentOrderProduct;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.*;
import com.zbkj.common.response.UserInfoResponse;
import com.zbkj.common.result.CommonResult;
import com.zbkj.common.utils.CrmebDateUtil;
import com.zbkj.common.vo.GroupInviteVO;
import com.zbkj.service.dao.GroupMessageDTO;
import com.zbkj.service.service.*;
import com.zbkj.service.util.AlibabaContentModerationUtil;
import com.zbkj.service.util.WeChatContentModerationUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.swing.border.TitledBorder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@RestController
@RequestMapping("api/front/together")
@Api(tags = "共创控制器")
public class TogetherController {

    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Autowired
    private UserTogetherService userTogetherService;

    @Autowired
    private AppealService appealService;

    @Autowired
    private UserTagService userTagService;

    @Autowired
    private TogetherJobService togetherJobService;

    @Autowired
    private IGroupMessageService groupMessageService;

    @Autowired
    private UserTogetherProductService userTogetherProductService;

    @Autowired
    private UserTogetherRecordService userTogetherRecordService;

    @Autowired
    private ProductService productService;

    @Autowired
    private TogetherAttachService togetherAttachService;

//    @Autowired
//    private IGroupMessageService groupMessageService;

    @Autowired
    private IGroupMemberService groupMemberService;

    @Autowired
    private IGroupService groupService;

    @Autowired
    private TbJobService tbJobService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserTogetherDemandService userTogetherDemandService;

    @Autowired
    ZoneUserTagService zoneUserTagService;

    @Autowired
    private WeChatContentModerationUtil weChatContentModerationUtil;

    @Autowired
    private AlibabaContentModerationUtil alibabaContentModerationUtil;

//
//    @Autowired
//    private TbJobService tbJobService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private TogetherJobExamService togetherJobExamService;


    @ApiOperation(value = "创建共创")
    @RequestMapping(value = "/addTogether", method = RequestMethod.POST)
    public CommonResult<Object> addTogether(@RequestBody @Validated UserTogether userTogether) throws Exception {

        /**
         * 审查内容是否违规
         */
        String openId = userTogether.getOpenId();
        if (StrUtil.isNotBlank(openId)) {
            //审查标题文字是否违规
            if (StrUtil.isNotBlank(userTogether.getTitle()))
                weChatContentModerationUtil.msgSecCheck(openId, userTogether.getTitle());
            //审查介绍文字是否违规
            if (StrUtil.isNotBlank(userTogether.getIntroduction()))
                weChatContentModerationUtil.msgSecCheck(openId, userTogether.getIntroduction());

            if (StrUtil.isNotBlank(userTogether.getImage())) {
                //OSS的桶名
                String urlPrefix = "https://img.zhuanz.net/";
                //获取图片列表
                String imgUrl = urlPrefix + userTogether.getImage();
                alibabaContentModerationUtil.imageCheck(imgUrl);
            }
        }

        Integer userId = userService.getUserIdException();
        User user = userService.getInfo();
        userTogether.setUid(userId);
        Date nowDate = CrmebDateUtil.nowDateTime();
        userTogether.setCreateTime(nowDate);
        userTogetherService.save(userTogether);
        TogetherJob togetherJob = new TogetherJob();
        togetherJob.setUid(userId);
        togetherJob.setStatus(3);
        togetherJob.setIsPay(1);
        togetherJob.setTogetherId(userTogether.getId());
        togetherJob.setCreateTime(nowDate);
        togetherJobService.save(togetherJob);
        String[] split = userTogether.getJobIds().split(",");
        if (StrUtil.isNotBlank(String.join("",split))) {
            for (String i : split) {
                TogetherJob s = new TogetherJob();
                s.setJobId(Integer.valueOf(i));
                s.setStatus(0);
                s.setIsPay(0);
                s.setTogetherId(userTogether.getId());
                s.setCreateTime(nowDate);
                togetherJobService.save(s);
            }
        }
        if (userTogether.getProductIds() != null && !userTogether.getProductIds().equals("")) {
            List<Long> productList = Arrays.stream(userTogether.getProductIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
            List<UserTogetherProduct> userTogetherProductList = new ArrayList<>();
            if (productList.size() > 0) {
                for (Long i : productList) {
                    UserTogetherProduct userTogetherProduct = new UserTogetherProduct();
                    userTogetherProduct.setProductId(i.intValue());
                    userTogetherProduct.setTogetherId(userTogether.getId());
                    userTogetherProduct.setCreateTime(nowDate);
                    userTogetherProductList.add(userTogetherProduct);

                }
                userTogetherProductService.saveBatch(userTogetherProductList);
            }
        }
        UserTogetherRecord userTogetherRecord = new UserTogetherRecord();
        userTogetherRecord.setTitle("我们的共创在这里开始");
        userTogetherRecord.setContent(userTogether.getProductIds());
        userTogetherRecord.setType(1);
        userTogetherRecord.setCreateTime(nowDate);
        userTogetherRecordService.save(userTogetherRecord);

        if (StrUtil.isNotBlank(userTogether.getFileUrls())) {
            String[] urlsArray = userTogether.getFileUrls().split(",");
            List<String> urlsList = Arrays.asList(urlsArray);
            urlsList.forEach(item -> {
                TogetherAttach togetherAttach = new TogetherAttach();
                String[] parts = item.split("/");
                String fileName = parts[parts.length - 1];
                int dotIndex = fileName.lastIndexOf('.');
                String name = (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex);
                String extension = (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
                togetherAttach.setUid(userId);
                togetherAttach.setFileName(userTogether.getFileName());
                togetherAttach.setFileExt(extension);
                togetherAttach.setTogetherId(userTogether.getId());
                togetherAttach.setFileUrl(systemAttachmentService.clearPrefix(item));
                togetherAttachService.save(togetherAttach);
            });
        }
        Group group = new Group();
        group.setName(userTogether.getTitle() + "共创群");
        group.setOwnerId(userTogether.getUid().longValue());

        group.setHeadImage(userTogether.getImage());
        group.setHeadImageThumb(userTogether.getImage());
        group.setTogetherId(userTogether.getId());
        groupService.save(group);


        GroupMember groupMember = new GroupMember();
//        gm.setUserId(Long.valueOf(userId));
        groupMember.setGroupId(group.getId());
        groupMember.setUserId(Long.valueOf(userId));
        groupMember.setHeadImage(user.getAvatar());
        groupMember.setAliasName(user.getNickname());
//            groupMember.setRemark(StringUtils.isEmpty(vo.getRemark()) ? group.getName() : vo.getRemark());
        groupMemberService.save(groupMember);


        GroupMessage groupMessage = new GroupMessage();
        groupMessage.setContent("共创群创建");
        groupMessage.setType(0);
        groupMessage.setSendId(Long.valueOf(user.getId()));
        groupMessage.setSendNickName(user.getNickname());
        groupMessage.setGroupId(group.getId());

        LocalDateTime now = LocalDateTime.now();

        // 计算当前时间的2秒后
        LocalDateTime timeAfterTwoSeconds = now.plus(5, ChronoUnit.SECONDS);
        Date date = Date.from(timeAfterTwoSeconds.atZone(ZoneId.systemDefault()).toInstant());
        groupMessage.setSendTime(date);
        groupMessageService.save(groupMessage);

        return CommonResult.success(userTogether.getId());
    }

    @ApiOperation(value = "修改共创内容")
    @RequestMapping(value = "/editTogether", method = RequestMethod.POST)
    public CommonResult<Object> editTogether(@RequestBody @Validated UserTogether togetherJob) {
        Integer userId = userService.getUserIdException();
        UserTogether userTogether = userTogetherService.getById(togetherJob.getId());
        if (userTogether.getUid() != userId)
            throw new CrmebException("并非共创发布者");
        userTogetherService.saveOrUpdate(togetherJob);
        return CommonResult.success("修改共创内容成功   ");
    }

    @ApiOperation(value = "创建共创角色")
    @RequestMapping(value = "/addTogetherJob", method = RequestMethod.POST)
    public CommonResult<Object> addTogetherJob(@RequestBody @Validated TogetherJob togetherJob) {
        Integer userId = userService.getUserIdException();
        Date nowDate = CrmebDateUtil.nowDateTime();
        togetherJob.setCreateTime(nowDate);
//        togetherJob.setUid(userId);
        togetherJobService.save(togetherJob);
        return CommonResult.success();
    }

//    @ApiOperation(value = "查看角色详情")
//    @RequestMapping(value = "/togetherJobInfo", method = RequestMethod.GET)
//    public CommonResult<Object> togetherJobInfo(Integer togetherId) {
//        TogetherJob togetherJobServiceById = togetherJobService.getById(togetherId);
//        return CommonResult.success(togetherJobServiceById);
//    }

    @ApiOperation(value = "共创角色列表")
    @RequestMapping(value = "/togetherJobList", method = RequestMethod.GET)
    public CommonResult<Object> togetherJobList(Integer togetherId) {
        Integer userId = userService.getUserIdException();
        LambdaQueryWrapper<TogetherJob> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(TogetherJob::getUid, userId);
        queryWrapper.eq(TogetherJob::getIsDel, 0);
        queryWrapper.eq(TogetherJob::getTogetherId, togetherId);
        List<TogetherJob> list = togetherJobService.list(queryWrapper);
        list.stream().map(togetherJob -> {
            if (togetherJob.getJobId() == null) {
                togetherJob.setJobName("发起人");
            } else {
                UserTag userTag = userTagService.getById(togetherJob.getJobId());
                togetherJob.setJobName(userTag.getName());
            }

            togetherJob.setUser(userService.getById(togetherJob.getUid()));

            //获取当前角色的试稿用户
            LambdaQueryWrapper<TogetherJobExam> lqw = new LambdaQueryWrapper<>();
            lqw.eq(TogetherJobExam::getTogetherJobId, togetherJob.getId());
//            lqw.lt(TogetherJobExam::getStatus,4);
            lqw.eq(TogetherJobExam::getIsDel, 0);
            List<TogetherJobExam> list1 = togetherJobExamService.list(lqw);
            List<User> userList = list1.stream().map(e -> {
                User u = userService.getById(e.getUid());
                u.setExamStatus(e.getStatus());
                return u;
            }).collect(Collectors.toList());
            togetherJob.setExamUsers(userList);

            if (togetherJob.getUid() != null) {
                LambdaQueryWrapper<Appeal> appealLambdaQueryWrapper = new LambdaQueryWrapper<>();
                appealLambdaQueryWrapper.eq(Appeal::getTogetherId, togetherId);
                appealLambdaQueryWrapper.eq(Appeal::getTargetUid, togetherJob.getUid());
                Appeal appeal = appealService.getOne(appealLambdaQueryWrapper);
                if (ObjectUtil.isNotNull(appeal))
                    togetherJob.setAppeal(appeal);
            }

            return togetherJob;
        }).collect(Collectors.toList());

        Collections.sort(list, Comparator.comparing(TogetherJob::getUid, Comparator.nullsFirst(Comparator.naturalOrder())));
        return CommonResult.success(list);
    }

    @ApiOperation(value = "共创角色列表详情")
    @RequestMapping(value = "/togetherJobInfo", method = RequestMethod.GET)
    public CommonResult<Object> togetherJobInfo(Integer id) {
        TogetherJob togetherJob = togetherJobService.getById(id);

        togetherJob.setUser(userService.getById(togetherJob.getUid()));
        if (togetherJob.getJobId() == null) {
            togetherJob.setJobName("发起者");
        } else {
            UserTag userTag = userTagService.getById(togetherJob.getJobId());
            togetherJob.setJobName(userTag.getName());

        }


        return CommonResult.success(togetherJob);
    }

    @ApiOperation(value = "设置共创角色")
    @RequestMapping(value = "/editTogetherJob", method = RequestMethod.POST)
    public CommonResult<Object> editTogetherJob(@RequestBody @Validated TogetherJob togetherJob) {
        Integer userId = userService.getUserIdException();
        Date nowDate = CrmebDateUtil.nowDateTime();
        togetherJob.setUpdateTime(nowDate);
        togetherJobService.saveOrUpdate(togetherJob);
        return CommonResult.success();
    }


    @ApiOperation(value = "同意加入共创角色(通过链接)")
    @RequestMapping(value = "/authorTogetherJob", method = RequestMethod.POST)
    public CommonResult<Object> authorTogetherJob(@RequestBody @Validated TogetherJob togetherJob) {
        LambdaQueryWrapper<TogetherJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TogetherJob::getJobId, togetherJob.getJobId());
        queryWrapper.eq(TogetherJob::getIsDel, 0);
        queryWrapper.eq(TogetherJob::getStatus, 3);
        queryWrapper.eq(TogetherJob::getTogetherId, togetherJob.getTogetherId());
        TogetherJob byId = togetherJobService.getOne(queryWrapper);

        UserTogether userTogether = userTogetherService.getById(togetherJob.getTogetherId());
        Integer userId = userService.getUserIdException();
        User user = userService.getById(userId);
        User userOne = userService.getById(userTogether.getUid());
        togetherJob.setStatus(3);
        if (byId == null) {
//            GroupInviteVO vo=new GroupInviteVO();
//            vo.setGroupId(group.getId().longValue());
            //            List<Long> userList = new ArrayList<>();
//            userList.add(userId.longValue());
//            groupService.invite(vo);
            LambdaQueryWrapper<Group> groupLambdaQueryWrapper = new LambdaQueryWrapper<>();
            groupLambdaQueryWrapper.eq(Group::getTogetherId, userTogether.getId());
            groupLambdaQueryWrapper.eq(Group::getDeleted, 0);
            Group one = groupService.getOne(groupLambdaQueryWrapper);
            Group group = new Group();
            if (one == null) {
                throw new CrmebException("加入群聊出错");
            } else {
                group = one;
            }


            LambdaQueryWrapper<GroupMember> groupMemberLambdaQueryWrapper = new LambdaQueryWrapper<>();
            groupMemberLambdaQueryWrapper.eq(GroupMember::getUserId, Long.valueOf(user.getId()));
            groupMemberLambdaQueryWrapper.eq(GroupMember::getGroupId, group.getId());
            GroupMember gm = groupMemberService.getOne(groupMemberLambdaQueryWrapper);

            GroupMember groupMember = new GroupMember();
            if (gm == null) {
                groupMember.setGroupId(group.getId());
                groupMember.setUserId(Long.valueOf(user.getId()));
                groupMember.setHeadImage(user.getAvatar());
                groupMember.setAliasName(user.getNickname());
//            groupMember.setRemark(StringUtils.isEmpty(vo.getRemark()) ? group.getName() : vo.getRemark());
                groupMemberService.save(groupMember);
            }


//            LambdaQueryWrapper<GroupMember> memberLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            memberLambdaQueryWrapper.eq(GroupMember::getUserId,Long.valueOf(user.getId()));
//            memberLambdaQueryWrapper.eq(GroupMember::getGroupId,userOne.getId());
//            GroupMember gmOne = groupMemberService.getOne(memberLambdaQueryWrapper);
//            if (gmOne==null) {
//                GroupMember groupMemberOne = new GroupMember();
//                groupMemberOne.setGroupId(group.getId());
//                groupMemberOne.setUserId(Long.valueOf(userOne.getId()));
//                groupMemberOne.setHeadImage(userOne.getAvatar());
//                groupMember.setAliasName(user.getNickname());
////            groupMember.setRemark(StringUtils.isEmpty(vo.getRemark()) ? group.getName() : vo.getRemark());
//                groupMemberService.save(groupMemberOne);
//            }


//            log.info("创建群聊，群聊id:{},群聊名称:{}", group.getId(), group.getName());


            GroupMessageDTO messageDTO = new GroupMessageDTO();
            messageDTO.setGroupId(group.getId().longValue());
            messageDTO.setType(0);
            messageDTO.setContent(user.getNickname());
            messageDTO.setUserId(userId.longValue());
            messageDTO.setSendNickName(user.getNickname());
            groupMessageService.sendUserMessage(messageDTO);

            queryWrapper.clear();
            queryWrapper.eq(TogetherJob::getJobId, togetherJob.getJobId());
            queryWrapper.eq(TogetherJob::getIsDel, 0);
            queryWrapper.eq(TogetherJob::getStatus, 0);
            queryWrapper.eq(TogetherJob::getTogetherId, togetherJob.getTogetherId());
            TogetherJob res = togetherJobService.getOne(queryWrapper);
            togetherJob.setId(res.getId());
            togetherJob.setUid(userId);
            togetherJobService.saveOrUpdate(togetherJob);

            UserTogetherRecord userTogetherRecord = new UserTogetherRecord();
            userTogetherRecord.setContent(user.getNickname() + "加入了共创");
            userTogetherRecord.setImg(user.getAvatar());
            userTogetherRecord.setTogetherId(userId);
            userTogetherRecord.setType(3);
            userTogetherRecord.setUid(userId);
            userTogetherRecordService.save(userTogetherRecord);
        } else {
            return CommonResult.failed("该共创角色已经被绑定了");
        }
        return CommonResult.success();
    }

    //分红定时任务处理商品问题
    @ApiOperation(value = "共创下拉框（前端）包含角色下拉框联动")
    @RequestMapping(value = "/getMyTogether", method = RequestMethod.GET)
    public CommonResult<Object> getMyTogether() {
        Integer userId = userService.getUserIdException();
        LambdaQueryWrapper<UserTogether> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserTogether::getUid, userId);
        queryWrapper.eq(UserTogether::getIsDel, 0);
        queryWrapper.orderByDesc(UserTogether::getId);
        List<UserTogether> list = userTogetherService.list(queryWrapper);
        list.stream().map(i -> {
            LambdaQueryWrapper<TogetherJob> togetherJobLambdaQueryWrapper = new LambdaQueryWrapper<>();
            togetherJobLambdaQueryWrapper.eq(TogetherJob::getTogetherId, i.getId());
            togetherJobLambdaQueryWrapper.eq(TogetherJob::getIsDel, 0);
            togetherJobLambdaQueryWrapper.eq(TogetherJob::getStatus, 0);
            //未加入
            List<TogetherJob> togetherJobList = togetherJobService.list(togetherJobLambdaQueryWrapper);
            for (TogetherJob togetherJob : togetherJobList) {
                if (togetherJob.getJobId() == null) {
                    togetherJob.setJobName("发起者");
                } else {
                    UserTag userTag = userTagService.getById(togetherJob.getJobId());
                    togetherJob.setJobName(userTag.getName());
                }
            }
            i.setTogetherJob(togetherJobList);
            return i;
        }).collect(Collectors.toList());
        return CommonResult.success(list);
    }


    //分红统计表


    @ApiOperation(value = "拒绝申请加入共创角色")
    @RequestMapping(value = "/refuseTogetherJob", method = RequestMethod.POST)
    public CommonResult<Object> refuseTogetherJob(@RequestBody @Validated TogetherJob togetherJob) {
        TogetherJob byId = togetherJobService.getById(togetherJob.getId());
        Integer userId = userService.getUserIdException();
        User user = userService.getById(userId);
        if (!byId.getJobId().equals(user.getJobId())) {
            return CommonResult.failed("你的角色跟当前共创角色不一致");
        }
        togetherJobService.saveOrUpdate(togetherJob);
        return CommonResult.success();
    }


    @ApiOperation(value = "我参与的")
    @RequestMapping(value = "/myTogetherJobList", method = RequestMethod.GET)
    public CommonResult<PageInfo<TogetherJob>> myTogetherJobList(@ModelAttribute @Validated PageParamRequest pageParamRequest, @RequestParam(value = "status") Integer status) {
        Integer userId = userService.getUserIdException();
        Page<TogetherJob> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<TogetherJob> list = new ArrayList<>();
        LambdaQueryWrapper<TogetherJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TogetherJob::getUid, userId);
        queryWrapper.eq(TogetherJob::getIsDel, 0);
        queryWrapper.eq(TogetherJob::getStatus, status);
//        queryWrapper.eq(TogetherJob::getJobId,jobId);
        list = togetherJobService.list(queryWrapper);
        list.stream().map(togetherJob -> {
            UserTogether userTogether = userTogetherService.getById(togetherJob.getTogetherId());
            togetherJob.setIsPay(userTogether.getIsPay());
            togetherJob.setIsProject(userTogether.getIsProject());
            togetherJob.setIsTogether(userTogether.getIsTogether());
            togetherJob.setUserTogether(userTogether);
            togetherJob.setUser(userService.getById(userTogether.getUid()));

            List<UserTag> list1 = userTagService.list();
            for (UserTag userTag : list1) {
                boolean contains = userTogether.getId().toString().contains(userTag.getId().toString());
                if (contains) {
                    userTag.setStatus(1);
                } else {
                    userTag.setStatus(0);
                }
            }
            togetherJob.setJobs(list1);
            return togetherJob;
        }).collect(Collectors.toList());
        PageInfo<TogetherJob> togetherJobPageInfo = CommonPage.copyPageInfo(page, list);
        return CommonResult.success(togetherJobPageInfo);
    }

    @ApiOperation(value = "任务大厅")
    @RequestMapping(value = "/myTaskHallList", method = RequestMethod.GET)
    public CommonResult<PageInfo<TogetherJob>> myTaskHallList(@ModelAttribute @Validated PageParamRequest pageParamRequest) {
//        Integer userId = userService.getUserIdException();
        Page<TogetherJob> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<TogetherJob> list = new ArrayList<>();
        LambdaQueryWrapper<TogetherJob> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(TogetherJob::getIsDel, 0);
//        queryWrapper.eq(TogetherJob::getStatus, 0);
//        queryWrapper.eq(TogetherJob::getJobId,jobId);
        queryWrapper.groupBy(TogetherJob::getTogetherId);
        //根据修改时间降序排序
        queryWrapper.orderByDesc(TogetherJob::getUpdateTime);

        //SELECT * FROM tb_together_job GROUP BY together_id;
        list = togetherJobService.list(queryWrapper);

        //填充封装TogetherJob
        fillTogetherJob(list);

        PageInfo<TogetherJob> togetherJobPageInfo = CommonPage.copyPageInfo(page, list);
        return CommonResult.success(togetherJobPageInfo);
    }

    /**
     * 填充封装TogetherJob
     *
     * @param list
     */
    private void fillTogetherJob(List<TogetherJob> list) {
        list.stream().map(togetherJob -> {
            LambdaQueryWrapper<TogetherJob> notQ = new LambdaQueryWrapper<>();

            notQ.eq(TogetherJob::getIsDel, 0);
//            notQ.eq(TogetherJob::getStatus, 0);
            notQ.isNotNull(TogetherJob::getJobId);
            notQ.eq(TogetherJob::getTogetherId, togetherJob.getTogetherId());
            //togetherJobService.list(notQ):  SELECT * FROM tb_together_job WHERE is_del = 0 AND job_id is not NULL AND together_id IN (SELECT together_id FROM tb_together_job GROUP BY together_id)
            //第一轮collect获取的值:4,1,2,4,1
            List<Integer> collect = togetherJobService.list(notQ).stream().map(TogetherJob::getJobId).collect(Collectors.toList());
            //第一轮:SELECT * FROM tb_user_together WHERE id = 7
            UserTogether userTogether = userTogetherService.getById(togetherJob.getTogetherId());
//            togetherJob.setIsPay(userTogether.getIsPay());
            //将userTogether的值赋值给togetherJob
            togetherJob.setIsProject(userTogether.getIsProject());
            togetherJob.setIsTogether(userTogether.getIsTogether());
            togetherJob.setIsPay(userTogether.getIsPay());
            togetherJob.setUserTogether(userTogether);
            togetherJob.setUser(userService.getById(userTogether.getUid()));
            LambdaQueryWrapper<UserTag> notM = new LambdaQueryWrapper<>();
//            notM.eq(UserTag::getIsDel, 0);
            if(CollUtil.isNotEmpty(collect))
                notM.in(UserTag::getId, collect);
            //第一轮:SELECT * FROM eb_user_tag WHERE id IN (4,1,2,4,1)
            List<UserTag> list1 = userTagService.list(notM);

//            UserTag userTag = userTagService.getById(togetherJob.getJobId());
//            togetherJob.setJobName(userTag.getName());

            togetherJob.setJobs(list1);
            return togetherJob;
        }).collect(Collectors.toList());
    }

    @ApiOperation(value = "根据关键词模糊查询共创")
    @RequestMapping(value = "/TogetherLikeTitle", method = RequestMethod.GET)
    public CommonResult<PageInfo<TogetherJob>> userTogetherLikeTitle(@ModelAttribute @Validated PageParamRequest pageParamRequest,
                                                                     @RequestParam(value = "keyword") String keyword) {

        //参数校验
        if (StrUtil.isBlank(keyword)) {
            return myTaskHallList(pageParamRequest);
        }

        Page<TogetherJob> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //获取userTogetherIds
        LambdaQueryWrapper<UserTogether> utlqw = new LambdaQueryWrapper<>();
        utlqw.select(UserTogether::getId)
                .eq(UserTogether::getIsPrivate,"0")
                .eq(UserTogether::getIsDel,"0")
                .like(UserTogether::getIntroduction,keyword)
                .or()
                .like(UserTogether::getTitle, keyword);
        List<Integer> userTogetherIds = userTogetherService.listObjs(utlqw).stream().map(id -> (Integer) id).collect(Collectors.toList());

        if (CollUtil.isEmpty(userTogetherIds)) {
            //获取togetherJob的条件
            LambdaQueryWrapper<TogetherJob> tjlqw = new LambdaQueryWrapper<>();
            tjlqw.eq(TogetherJob::getTogetherId, -1);
            List<TogetherJob> list = togetherJobService.list(tjlqw);
            PageInfo<TogetherJob> togetherJobPageInfo = CommonPage.copyPageInfo(page, list);
            return CommonResult.success(togetherJobPageInfo);
        }
        //获取togetherJob的条件
        LambdaQueryWrapper<TogetherJob> tjlqw = new LambdaQueryWrapper<>();
        tjlqw.in(TogetherJob::getTogetherId, userTogetherIds)
                .eq(TogetherJob::getIsDel,0)
                .groupBy(TogetherJob::getTogetherId)
                .orderByDesc(TogetherJob::getUpdateTime);

        //获取togetherJob
        List<TogetherJob> list = togetherJobService.list(tjlqw);

        //填充封装TogetherJob
        fillTogetherJob(list);

        PageInfo<TogetherJob> togetherJobPageInfo = CommonPage.copyPageInfo(page, list);
        return CommonResult.success(togetherJobPageInfo);
    }

    @ApiOperation(value = "根据板块查共创")
    @RequestMapping(value = "/togetherByZone", method = RequestMethod.GET)
    public CommonPage<UserTogether> togetherByZone(@RequestParam("zone") Integer zone, @ModelAttribute @Validated PageParamRequest pageParamRequest) {
        Integer userId = userService.getUserIdException();
        Page<UserTogether> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<ZoneUserTag> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ZoneUserTag::getZone, zone);
        lqw.eq(ZoneUserTag::getIsDel, 0);
        List<ZoneUserTag> list = zoneUserTagService.list(lqw);

        LambdaQueryWrapper<UserTogether> lqw2 = new LambdaQueryWrapper<>();
        boolean[] isFirst = {true};

        list.forEach(item -> {
            if (isFirst[0]) {
                isFirst[0] = false;
                lqw2.apply("FIND_IN_SET(" + item.getTagId() + ", job_ids) > 0");
            } else {
                lqw2.or();
                lqw2.apply("FIND_IN_SET(" + item.getTagId() + ", job_ids) > 0");
            }

        });

        List<UserTogether> response = userTogetherService.list(lqw2);
        return CommonPage.restPage(CommonPage.copyPageInfo(page, response));
    }


    @ApiOperation(value = "根据板块查共创")
    @RequestMapping(value = "/togetherByZoneV2", method = RequestMethod.GET)
    public CommonPage<TogetherJob> togetherByZoneV2(@RequestParam("zone") Integer zone, @ModelAttribute @Validated PageParamRequest pageParamRequest) {
//        Integer userId = userService.getUserIdException();

        LambdaQueryWrapper<ZoneUserTag> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ZoneUserTag::getZone, zone);
        lqw.eq(ZoneUserTag::getIsDel, 0);
        List<ZoneUserTag> list = zoneUserTagService.list(lqw);

        List<Integer> IdsList = list.stream().map(e -> e.getTagId()).collect(Collectors.toList());

        if (IdsList.isEmpty())
            return null;
        LambdaQueryWrapper<TogetherJob> lqw11 = new LambdaQueryWrapper<>();
        lqw11.in(TogetherJob::getJobId, IdsList);
        Page<TogetherJob> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<TogetherJob> respongseList = togetherJobService.list(lqw11);

        respongseList = respongseList.stream().map(e -> {
            e.setUserTogether(userTogetherService.getById(e.getTogetherId()));
            UserTag userTag = userTagService.getById(e.getJobId());
            e.setJobName(userTag.getName());
            return e;
        }).collect(Collectors.toList());

        return CommonPage.restPage(CommonPage.copyPageInfo(page, respongseList));
    }

    @ApiOperation(value = "查看共创详情")
    @RequestMapping(value = "/userTogetherInfo", method = RequestMethod.GET)
    public CommonResult<Object> userTogetherInfo(@RequestParam(value = "id") Integer id) {
        UserTogether userTogether = userTogetherService.getById(id);
        List<TogetherJob> list = new ArrayList<>();
        LambdaQueryWrapper<TogetherJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TogetherJob::getTogetherId, id);
        queryWrapper.eq(TogetherJob::getIsDel, 0);
        queryWrapper.eq(TogetherJob::getStatus, 0);
        //未加入
//        list = togetherJobService.list(queryWrapper);
//        list.stream().map(togetherJob -> {
//            togetherJob.setUser(userService.getById(togetherJob.getUid()));
//
//            return togetherJob;
//        }).collect(Collectors.toList());


        list = togetherJobService.list(queryWrapper);
        list.stream().map(togetherJob -> {
            togetherJob.setUser(userService.getById(togetherJob.getUid()));

            UserTag userTag = userTagService.getById(togetherJob.getJobId());
            togetherJob.setJobName(userTag.getName());
//            TbJob byId = tbJobService.getById(togetherJob.getJobId());

            return togetherJob;
        }).collect(Collectors.toList());

        HashMap map = new HashMap();
        //已加入
        LambdaQueryWrapper<TogetherJob> queryWrapperEnter = new LambdaQueryWrapper<>();
        queryWrapperEnter.eq(TogetherJob::getTogetherId, id);
        queryWrapperEnter.eq(TogetherJob::getIsDel, 0);
        queryWrapperEnter.eq(TogetherJob::getStatus, 3);

        List<TogetherJob> listEnter = togetherJobService.list(queryWrapperEnter);
        listEnter.stream().map(togetherJob -> {
            togetherJob.setUser(userService.getById(togetherJob.getUid()));
            if (togetherJob.getJobId() == null) {
                togetherJob.setJobName("发起者");
            } else {
                UserTag userTag = userTagService.getById(togetherJob.getJobId());
                togetherJob.setJobName(userTag.getName());
            }

            return togetherJob;
        }).collect(Collectors.toList());
        map.put("listNotEnter", list);
        map.put("listEnter", listEnter);

        LambdaQueryWrapper<UserTogetherRecord> userTogetherRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userTogetherRecordLambdaQueryWrapper.eq(UserTogetherRecord::getTogetherId, id);
        userTogetherRecordLambdaQueryWrapper.eq(UserTogetherRecord::getIsDel, 0);
        userTogetherRecordLambdaQueryWrapper.orderByDesc(UserTogetherRecord::getCreateTime);
        List<UserTogetherRecord> userTogetherRecords = userTogetherRecordService.list(userTogetherRecordLambdaQueryWrapper);
        userTogetherRecords.stream().map(record -> {
//            if (record.getType()==1) {
//                List<Long> productList = Arrays.stream(record.getContent().split(",")).map(Long::parseLong).collect(Collectors.toList());
//                LambdaQueryWrapper<Product> productLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                productLambdaQueryWrapper.in(Product::getId,productList);
//                productLambdaQueryWrapper.eq(Product::getIsDel, 0);
//                List<Product> products = productService.list(productLambdaQueryWrapper);
//                record.setProduct(products);
//            }
            record.setUser(userService.getById(record.getUid()));
            return record;
        }).collect(Collectors.toList());
        map.put("userTogetherRecords", userTogetherRecords);
        map.put("userTogether", userTogether);

        LambdaQueryWrapper<Group> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(Group::getTogetherId, id);
        Group group = groupService.getOne(lqw1);
        map.put("group", group);
        return CommonResult.success(map);
    }


    @ApiOperation(value = "新增共创任务")
    @RequestMapping(value = "/addUserTogetherDemand", method = RequestMethod.POST)
    public CommonResult<Object> addUserTogetherDemand(@RequestBody @Validated UserTogetherDemand userTogetherDemand) {
        Integer userId = userService.getUserIdException();
        Date nowDate = CrmebDateUtil.nowDateTime();
        userTogetherDemand.setUpdateTime(nowDate);
        userTogetherDemand.setCreateTime(nowDate);
        userTogetherDemandService.save(userTogetherDemand);
        return CommonResult.success();
    }

    @ApiOperation(value = "查询共创任务下拉框")
    @RequestMapping(value = "/getDemandForUser", method = RequestMethod.GET)
    public CommonResult<Object> getDemandForUser(@RequestParam(value = "togetherId") Integer togetherId) {
        Integer userId = userService.getUserIdException();
        List<TogetherJob> list = new ArrayList<>();
        LambdaQueryWrapper<TogetherJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TogetherJob::getTogetherId, togetherId);
        queryWrapper.eq(TogetherJob::getIsDel, 0);
        queryWrapper.isNotNull(TogetherJob::getJobId);
        queryWrapper.eq(TogetherJob::getStatus, 3);
        //未加入
        list = togetherJobService.list(queryWrapper);
        List<User> userList = new ArrayList<>();
        list.stream().map(togetherJob -> {
            User byId = userService.getById(togetherJob.getUid());
            byId.setUserJobId(togetherJob.getId());
            userList.add(byId);
            togetherJob.setUser(userService.getById(togetherJob.getUid()));
//                TbJob tbJob = tbJobService.getById(togetherJob.getJobId());
//                togetherJob.setJobName(tbJob.getJobName());
            UserTag userTag = userTagService.getById(togetherJob.getJobId());
            togetherJob.setJobName(userTag.getName());
            return togetherJob;


        }).collect(Collectors.toList());
        return CommonResult.success(userList);
    }

    @ApiOperation(value = "查询共创任务进度")
    @RequestMapping(value = "/getTogetherSchedule", method = RequestMethod.GET)
    public CommonResult<Object> getTogetherSchedule(@RequestParam(value = "togetherId") Integer togetherId) {
        Integer userId = userService.getUserIdException();
        List<UserTogetherDemand> list = new ArrayList<>();
        LambdaQueryWrapper<UserTogetherDemand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserTogetherDemand::getTogetherId, togetherId);
        queryWrapper.eq(UserTogetherDemand::getIsDel, 0);

        //未加入
        list = userTogetherDemandService.list(queryWrapper);
        list.stream().map(togetherJob -> {
            TogetherJob togetherJobServiceById = togetherJobService.getById(togetherJob.getUserJobId());
            togetherJob.setUser(userService.getById(togetherJob.getUid()));
            if (togetherJobServiceById.getJobId() == null) {
                togetherJob.setJobName("发起者");
            } else {
                UserTag userTag = userTagService.getById(togetherJobServiceById.getJobId());
                togetherJob.setJobName(userTag.getName());
            }


            return togetherJob;
        }).collect(Collectors.toList());
        return CommonResult.success(list);
    }


    @ApiOperation(value = "查询我的共创任务")
    @RequestMapping(value = "/getMyTogetherSchedule", method = RequestMethod.GET)
    public CommonResult<Object> getMyTogetherSchedule(@RequestParam(value = "togetherId") Integer togetherId) {
        Integer userId = userService.getUserIdException();
        List<UserTogetherDemand> list = new ArrayList<>();
        LambdaQueryWrapper<UserTogetherDemand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserTogetherDemand::getTogetherId, togetherId);
        queryWrapper.eq(UserTogetherDemand::getIsDel, 0);
        queryWrapper.eq(UserTogetherDemand::getUid, userId);
        //未加入
        list = userTogetherDemandService.list(queryWrapper);
        list.stream().map(togetherJob -> {
            TogetherJob togetherJobServiceById = togetherJobService.getById(togetherJob.getUserJobId());
            togetherJob.setUser(userService.getById(togetherJob.getUid()));
            if (togetherJobServiceById.getJobId() != null) {
//                TbJob tbJob = tbJobService.getById(togetherJobServiceById.getJobId());
//                togetherJob.setJobName(tbJob.getJobName());
                UserTag userTag = userTagService.getById(togetherJobServiceById.getJobId());
                togetherJob.setJobName(userTag.getName());
            }
            return togetherJob;


        }).collect(Collectors.toList());
        return CommonResult.success(list);
    }


    @ApiOperation(value = "修改共创任务状态")
    @RequestMapping(value = "/editMyTogetherSchedule", method = RequestMethod.GET)
    public CommonResult<Object> editMyTogetherSchedule(@RequestParam(value = "id") Integer id, @RequestParam(value = "status") Integer status) {
        UserInfoResponse userInfo = userService.getUserInfo();
        UserTogetherDemand byId = userTogetherDemandService.getById(id);
        Date nowDate = CrmebDateUtil.nowDateTime();
        byId.setUpdateTime(nowDate);
        byId.setStatus(status);
        userTogetherDemandService.saveOrUpdate(byId);
        UserTogetherRecord userTogetherRecord = new UserTogetherRecord();
        String oper = status == 1 ? "进行" : "完成";
        oper += "任务为：" + byId.getJobName() + "," + byId.getContent() + "的需求";
        userTogetherRecord.setUid(userInfo.getId());
        userTogetherRecord.setCreateTime(nowDate);
        userTogetherRecord.setTogetherId(byId.getTogetherId());
        userTogetherRecord.setContent("用户名:" + userInfo.getNickname() + oper);
        userTogetherRecordService.save(userTogetherRecord);
        return CommonResult.success();
    }

    @ApiOperation(value = "修改角色详情")
    @RequestMapping(value = "/editJobInfo", method = RequestMethod.POST)
    public CommonResult<Object> editJobInfo(@RequestBody @Validated TogetherJob togetherJob) {
        Date nowDate = CrmebDateUtil.nowDateTime();
        togetherJob.setUpdateTime(nowDate);
        togetherJobService.saveOrUpdate(togetherJob);
        return CommonResult.success();
    }


    @ApiOperation(value = "时间轴新增")
    @RequestMapping(value = "/recordAdd", method = RequestMethod.POST)
    public CommonResult<String> recordAdd(@RequestBody TogetherRecordAddRequest request) {
        try {
            Integer userId = userService.getUserId();
//            Integer userId = 2;
            UserTogetherRecord userTogetherRecord = new UserTogetherRecord();
            BeanUtils.copyProperties(request, userTogetherRecord);
            userTogetherRecord.setUid(userId);
            userTogetherRecordService.save(userTogetherRecord);
            return CommonResult.success("新增成功");
        } catch (Exception e) {
            return CommonResult.failed("新增失败");
        }
    }

    @ApiOperation(value = "时间轴删除")
    @RequestMapping(value = "/recordRemove", method = RequestMethod.GET)
    public CommonResult<String> recordRemove(@RequestParam Integer id) {
        try {
            Integer userId = userService.getUserId();
            UserTogetherRecord userTogetherRecord = userTogetherRecordService.getById(id);
            UserTogether userTogether = userTogetherService.getById(userTogetherRecord.getTogetherId());
            if (userTogether.getUid() != userId)
                throw new CrmebException("不是该共创的发起者");
            userTogetherRecordService.removeById(id);
            return CommonResult.success("删除成功");
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }

    @ApiOperation(value = "时间轴删除")
    @RequestMapping(value = "/recordUpdate", method = RequestMethod.POST)
    public CommonResult<String> recordUpdate(@RequestBody TogetherRecordAddRequest request) {
        try {
            Integer userId = userService.getUserId();
            UserTogetherRecord userTogetherRecord = userTogetherRecordService.getById(request.getId());
            UserTogether userTogether = userTogetherService.getById(userTogetherRecord.getTogetherId());
            if (userTogether.getUid() != userId)
                throw new CrmebException("不是该共创的发起者");
            BeanUtils.copyProperties(request, userTogetherRecord);
            userTogetherRecordService.saveOrUpdate(userTogetherRecord);
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }

    @ApiOperation(value = "共创关联目标")
    @RequestMapping(value = "/associate", method = RequestMethod.POST)
    public CommonResult<String> Associate(@RequestBody TogetherAssociateRequest request) {
        try {
            Integer userId = userService.getUserId();
            UserTogether userTogether = userTogetherService.getById(request.getTargetId());
            if (userTogether.getUid() != userId)
                throw new CrmebException("不是该共创的发起者");

            if (userTogether.getType() != request.getType())
                throw new CrmebException("目标类型与共创类型不匹配");

            userTogether.setTargetId(request.getTargetId());
            userTogetherService.updateById(userTogether);
            return CommonResult.success("关联成功");
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }

    @ApiOperation(value = "拿角色名字")
    @RequestMapping(value = "/getJob", method = RequestMethod.GET)
    public CommonResult<Object> getJob(@RequestParam Integer jobId, @RequestParam Integer togId) {
        try {
            String job = userTagService.getById(jobId).getName();
            UserTogether togetherJob = userTogetherService.getById(togId);
//            userTogetherService.updateById(userTogether);
            Map map = new HashMap<>();
            map.put("jobName", job);
            map.put("userTogether", togetherJob);
            return CommonResult.success(map);
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }

    @ApiOperation(value = "共创附件list")
    @RequestMapping(value = "/fileList", method = RequestMethod.GET)
    public CommonPage<TogetherAttach> fileList(@ModelAttribute @Validated TogetherZonePageReuqest request) {
        Page<Object> page = PageHelper.startPage(request.getPage(), request.getLimit());
        LambdaQueryWrapper<TogetherAttach> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TogetherAttach::getTogetherId, request.getTogetherId());
        List<TogetherAttach> list = togetherAttachService.list(lqw);
        return CommonPage.restPage(CommonPage.copyPageInfo(page, list));
    }

    @ApiOperation(value = "共创附件新增")
    @RequestMapping(value = "/fileAdd", method = RequestMethod.POST)
    public CommonResult<Boolean> fileAdd(@RequestBody TogetherAttachRequest request) {
        try {
            Integer userId = userService.getUserIdException();
            request.setUid(userId);
            TogetherAttach togetherAttach = new TogetherAttach();
            BeanUtils.copyProperties(request, togetherAttach);
            return CommonResult.success(togetherAttachService.save(togetherAttach));
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }

    @ApiOperation(value = "共创附件删除")
    @RequestMapping(value = "/fileDel", method = RequestMethod.GET)
    public CommonResult<Boolean> fileDel(@RequestParam Integer id) {
        try {
            Integer userId = userService.getUserIdException();
            return CommonResult.success(togetherAttachService.removeById(id));
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }


    @ApiOperation(value = "共创角色删除")
    @RequestMapping(value = "/jobDel", method = RequestMethod.GET)
    public CommonResult<Boolean> jobDel(@RequestParam Integer togetherJobId) {
        try {
            Integer userId = userService.getUserIdException();
            TogetherJob togetherJob = togetherJobService.getById(togetherJobId);
            LambdaQueryWrapper<UserTogether> lqw = new LambdaQueryWrapper<>();
            lqw.eq(UserTogether::getUid, userId);
//            lqw.eq(UserTogether::getIsDel,0);
            lqw.eq(UserTogether::getId, togetherJob.getTogetherId());
            UserTogether userTogether = userTogetherService.getOne(lqw);
            if (ObjectUtil.isNull(userTogether)) {
                throw new CrmebException("共创信息查找失败");
            }
            togetherJob.setIsDel(true);
            userTogether.setJobIds(removeFirstOccurrence(userTogether.getJobIds(), String.valueOf(togetherJob.getJobId())));
            return CommonResult.success(togetherJobService.updateById(togetherJob));
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }

    public static String removeFirstOccurrence(String input, String target) {
        Pattern pattern = Pattern.compile("(?:^|,)" + Pattern.quote(target) + "(?:,|$)");
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            return input.substring(0, matcher.start()) + input.substring(matcher.end());
        }
        return input;
    }


}
